const Service = require('egg').Service

class RegisterService extends Service {
	constructor(ctx) {
		super(ctx)
	}
	async index(body) {
		const { username, password, invitationCode } = body
		const hasInvitationCode = await this.ctx.model.InvitationCode.findOne({
			where: { status: 0, code: invitationCode },
		})
		if (hasInvitationCode == null) {
			return '无效的邀请码'
		} else {
			const hasOneSameName = await this.ctx.model.User.findOne({
				where: { username },
			})

			if (hasOneSameName) {
				return '存在相同数据'
			} else {
				await this.ctx.model.InvitationCode.update(
					{ status: 1 },
					{ where: { id: hasInvitationCode.id } }
				)

				const encryptPassword = this.ctx.helper.encrypt(password)
				const { id } = await this.ctx.model.User.create({
					username,
					password: encryptPassword,
					invitationCode,
				})

				await this.ctx.model.UserInfo.create({
					userId: id,
					name: username,
				})
				return 'success'
			}
		}
	}
}

module.exports = RegisterService
